<template>
	<view class="box">
		<view class="box_top">
			<text>预存运费</text>
		</view>
		<view class="content">
			<view class="content_shang">
				<view class="zhong">
					<view class="zhong_shang">
						<view class="shang_text">
							本次发布货源需预存运费
						</view>
						<view class="shang_text">
							<text>结算主体：山西创盟星河科技有限公司</text>
						</view>
					</view>
					<view class="zhong_zhong">
						<view class="zhong_text">
							<text>运费金额</text>
						</view>
					</view>
					<view class="zhong_xia">
						<view class="fee_details">
							<text class="amount">￥</text>
							<text class="amount">{{ paymentInfo.feeAmount }}</text>
						</view>
						<view class="fee_details">
							<text>含税运费：{{ paymentInfo.taxFee }}元</text>
						</view>
						<view class="fee_details">
							<text>保证金：{{ paymentInfo.depositFee }}元</text>
						</view>
					</view>
					<view class="balance">
						<text>可用余额(元)</text>
						<text>{{ paymentInfo.availableBalance }}</text>
					</view>
				</view>
			</view>
			<view class="content_xia">
				<view class="buttons">
					<button class="pay-button" @click="onPay">支付运费</button>
					<button class="reserve-button" @click="onReserve">稍后预存</button>
				</view>
			</view>
		</view>
		<uni-popup ref="popupRef" type="bottom" :mask-click="true">
			<view class="password-popup-bottom">
				<view class="popup-title">请输入支付密码</view>

				<input v-model="paymentPassword" type="number" maxlength="6" class="real-input" focus />

				<view class="custom-password-box">
					<view v-for="(item, index) in 6" :key="index" class="pwd-cell">
						<view v-if="index < paymentPassword.length" class="dot"></view>
					</view>
				</view>

				<view class="popup-buttons">
					<button class="popup-cancel" @click="popupRef.close()">取消</button>
					<button class="popup-confirm" @click="confirmPay">确认支付</button>

				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		http
	} from '../../../config/request.js';
	import {
		useuser
	} from '../../../stores/user.js';
	import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
	const duixiang = ref({});
	const car = ref([]);
	const popupRef = ref(null)
	const paymentPassword = ref('')
	const zhifu = ref(null)
	const user = useuser();
	const peizhidx = ref({});
	const paymentInfo = ref({
		feeAmount: '', // 运费金额
		taxFee: '', // 含税运费
		depositFee: '', // 保证金
		availableBalance: 0 // 可用余额
	});

	// 用于判断支付按钮是否禁用
	const isPayDisabled = ref(true);

	const peizhi = async () => {
		const res = await http({
			url: `/shipperConfig/select/${user.user.id}`,
			method: 'GET',
		});
		console.log('配置信息', res);

		if (res.code === 20041) {
			peizhidx.value = res.shuju;
		} else {
			uni.showToast({
				title: '货源配置获取失败',
				icon: 'none',
			});
		}
	};

	// 计算运费和保证金
	const calculatePaymentInfo = (data) => {
		// 计算保证金
		if (peizhidx.value.depositratio == 1) {
			var baifen = peizhidx.value.depositratioprice * 0.01;
			const baozhengjin = parseFloat(data.totalweight) * parseFloat(data.unitprice) * baifen;
			paymentInfo.value.depositFee = baozhengjin;
			console.log('保证金', baozhengjin);
		} else {
			paymentInfo.value.depositFee = '';
		}

		// 计算含税运费
		if (peizhidx.value.prepaymentratio == 1) {
			var baifen = peizhidx.value.prepaymentratioprice * 0.01;
			const huanshuiyunfei = parseFloat(data.totalweight) * parseFloat(data.unitprice) * baifen;
			console.log('含税运费', huanshuiyunfei);
			const zongyunfei = huanshuiyunfei + paymentInfo.value.depositFee;
			console.log('总运费', zongyunfei);
			paymentInfo.value.taxFee = huanshuiyunfei;
			paymentInfo.value.feeAmount = zongyunfei;
		}
	};
	const tijiao = async () => {
		duixiang.value.totalweights = duixiang.value.totalweight;
		console.log('提交的数据', duixiang.value);
		// 去掉 car.value 中每一项的 checked 字段
		const cleanCarList = car.value.map(item => {
			const {
				checked,
				...rest
			} = item;
			return rest;
		});

		// 如果 car.value 为空，不传递 car 字段
		const jihe = {
			duixiang: duixiang.value,
			car: cleanCarList.length > 0 ? cleanCarList : [] // 如果车队为空，传递空数组
		};
		const res = await http({
			url: '/addfreightsources',
			method: 'POST',
			data: jihe
		});
		console.log('提交结果', res);
		const xx = res.shuju
		console.log('提交结果', xx);
		if (res.code === 20011) {
			uni.removeStorageSync('chedui');

			uni.navigateTo({
				url: `/pages/sourceofgoods/pageinfo/fabuhuoyuan?sourceid=${xx}`,
			});
			// 返回货源发布页面 延时跳转
			// setTimeout(() => {
			// 	uni.switchTab({
			// 		url: '/pages/sourceofgoods/index',
			// 	})
			// }, 1500);
		} else {
			throw new Error(res.message || '发布失败');
		}
	}
	const xiugai = async () => {
		const xx = paymentInfo.value.availableBalance - paymentInfo.value.feeAmount
		console.log('修改后的余额', xx);
		paymentInfo.value.availableBalance = xx
		const can = {
			fid: user.user.id,
			balance: xx
		}
		const res = await http({
			url: '/updatefid',
			method: 'POST',
			data: can,
		});
		console.log('修改结果', res);

	}


	// 支付运费
	const onPay = () => {
		if (paymentInfo.value.availableBalance < paymentInfo.value.feeAmount) {
			uni.showToast({
				title: '余额不足，请先充值',
				icon: 'none',
				duration: 2000,
			});
			return;
		} else {
			duixiang.value.status = 4;
			duixiang.value.yprice = paymentInfo.value.feeAmount;
			popupRef.value.open();
			// tijiao()
			// xiugai()
		}
	};
	const confirmPay = () => {

		if (!zhifu.value) {
			uni.showModal({
				title: '提示',
				content: '您还未设置支付密码，是否前往设置？',
				confirmText: '去设置',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/sourceofgoods/pageinfo/zhifu' // 请替换成你的设置密码页面路径
						});
					}
				}
			});
			return;
		}
		if (paymentPassword.value.length !== 6) {
			uni.showToast({
				title: '请输入6位密码',
				icon: 'none',
			});
			return;
		}
		jiezhang()

	};
	const jiezhang = async () => {
		const res = await http({
			url: '/panduan',
			method: 'post',
			data: {
				fid: user.user.id,
				paymentPassword: paymentPassword.value
			}
		});
		if (res.code === 20041) {
			popupRef.value.close();
			duixiang.value.status = 4;
			duixiang.value.yprice = paymentInfo.value.feeAmount;
			tijiao();
			xiugai();
		} else {
			uni.showToast({
				title: '支付密码错误',
				icon: 'none',
				duration: 2000,
			});
			// 密码正确，执行支付流程
			paymentPassword.value = ''; // 清空密码输入框
		}
	}
	// 稍后预存
	const onReserve = () => {
		duixiang.value.status = 0;
		duixiang.value.yprice = 0;
		tijiao();


	};
	const qianbao = async () => {
		const qianbao = await http({
			url: '/getWallet/' + user.user.id,
			method: 'get',
		});
		console.log(qianbao)
		zhifu.value = qianbao.shuju.paymentPassword
		if (qianbao.code === 20041) {
			paymentInfo.value.availableBalance = qianbao.shuju.balance;
		} else {
			uni.showToast({
				title: '钱包信息获取失败',
				icon: 'none',
				duration: 2000,
			});
		}
	}
	onLoad((opt) => {
		// 加载页面时就开始请求数据并绑定值
		peizhi().then(() => {
			const data = JSON.parse(opt.data);
			console.log('传递的参数', data);
			duixiang.value = data;
			const chedui = JSON.parse(opt.chedui)
			car.value = chedui;
			console.log('chedui', chedui);
			// 计算运费和保证金
			calculatePaymentInfo(data);
			qianbao()
		});
	});
</script>

<style lang="scss">
	.popup-cancel {
		width: 200rpx;
		height: 80rpx;
		background-color: #fff;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #333;
		font-size: 30rpx;
		margin-left: 20rpx;
	}

	.popup-confirm {
		width: 200rpx;
		height: 80rpx;
		background-color: #fff;
		border-radius: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #333;
		font-size: 30rpx;
		margin-left: 20rpx;
	}

	.real-input {
		position: absolute;
		opacity: 0;
		width: 100%;
		height: 100rpx;
		top: 140rpx;
		z-index: 99;
	}

	// 白色底部弹出层
	.password-popup-bottom {
		width: 100%;
		padding: 40rpx 30rpx;
		background-color: #ffffff;
		border-radius: 20rpx 20rpx 0 0;
		box-shadow: 0 -6rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		color: #333;
		margin-bottom: 30rpx;
	}

	.custom-password-box {
		display: flex;
		justify-content: space-between;
		height: 100rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		background-color: #f9f9f9;
		position: relative;
		margin-bottom: 250rpx;
		margin-right: 65rpx;
	}

	.pwd-cell {
		flex: 1;
		border-right: 1rpx solid #e5e5e5;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.pwd-cell:last-child {
		border-right: none;
	}

	.dot {
		width: 20rpx;
		height: 20rpx;
		background-color: #333;
		border-radius: 50%;
	}

	.popup-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;

	}

	.box {
		background-color: #002fa7;
	}

	.box_top {
		line-height: 130rpx;
		padding-left: 40rpx;
		font-size: 40rpx;
		color: #fff;
	}

	.content {
		height: 88vh;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
	}

	.content_shang {
		width: 100%;
		height: 75%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
	}

	.zhong {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 600rpx;
		padding: 20rpx;
		border-radius: 10rpx;
	}

	.zhong_shang {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20rpx;
		color: #627fc9;
		margin-top: -120rpx;
		padding-bottom: 30rpx;
	}

	.shang_text {
		font-size: 25rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.zhong_zhong {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		margin-bottom: 50rpx;
	}

	.zhong_text {
		font-size: 30rpx;
		font-weight: bold;
		text-align: center;
	}

	.zhong_xia {
		display: flex;
		flex-direction: column;
		width: 100%;
		margin-bottom: 20rpx;
	}

	.fee_details {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 20rpx;
		color: #627fc9;
		font-size: 25rpx;
	}

	.amount {
		font-size: 50rpx;
		font-weight: bold;
		color: #fff;
		margin-left: 10rpx;
	}

	.balance {
		font-size: 28rpx;
		font-weight: bold;
		margin-top: 20rpx;
	}

	.balance :nth-child(1) {
		margin-right: 23rpx;
	}

	.content_xia {
		width: 100%;
		background-color: #eeeeee;
		border-radius: 20rpx 20rpx 0 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 25vh;
	}

	.buttons {
		width: 100%;
		padding: 0 20rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	button {
		width: 100%;
		padding: 15rpx;
		font-size: 36rpx;
		border-radius: 10rpx;
		text-align: center;
	}

	.pay-button {
		background-color: #002fa7;
		color: white;
		border: none;
		width: 500rpx;
		margin-top: 30rpx;
	}

	.reserve-button {
		background-color: #f0f0f0;
		color: #007aff;
		border: 1px solid #007aff;
		width: 500rpx;
	}

	.pay-button:disabled {
		background-color: #ccc;
	}
</style>